package me.pinion.controller;


import me.pinion.Log;
import me.pinion.check.annotation.AllowRole;
import me.pinion.controller.annotation.RouteBind;
import me.pinion.kit.CommonKit;
import me.pinion.model.*
import me.pinion.service.FavoriteService;

import javax.servlet.http.HttpServletResponse;

@RouteBind("/favorite")
public class FavoriteController extends Controller {

    FavoriteService favoriteService

    @AllowRole(["USER"])
    public void index(){

        String clazzStr = getPara("clazz");
        int targetId = getParaToInt("id");
        try {
            Class<? extends XModel> clazz = (Class<? extends XModel>) Class.forName(clazzStr);
            XModel model = (XModel) clazz.newInstance().findById(targetId);
            if (model == null){
                throw new NotFoundException();
            }
            Favorite favo = favoriteService.favo(model, this.<User>getSessionAttr("user"));
            if(getParaValues("tag[]") != null){
                for (String tag: getParaValues("tag[]")){
                    Tag.dao.findByName(CommonKit.urlVal2utf8(tag)).put(model);
                }
            }
            renderJson(favo);
        } catch (Exception e) {
            Log.e(e);
            renderError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @AllowRole(["user"])
    public void undo(){
        XModel model = ModelType.dao.getModel(getPara("clazz"), getParaToInt("id"));
        Favorite favo = Favorite.dao.favo(model, this.<User>getSessionAttr("user"));
        favo.delete();
        renderJson();
    }
}
